

package tomkitty;

import java.net.*;
import java.util.*;
import java.text.*;

public class TkResponse implements Response {

  protected Socket sock = null;
  protected String status = null;
  protected Hashtable<String, String> fields = new Hashtable<String, String>();
  protected final String CRLF = "\r\n";
  protected boolean headerIsSent = false;
  protected boolean headOnly = false;

  public Socket getSocket() { return sock; }
  public void setSocket(Socket sock) { this.sock = sock; }

  public String getStatus() { return status; }
  public void setStatus(String status) { this.status = status; }

  public String getField(String key) { return fields.get(key); }
  public void setField(String key, String value) { fields.put(key, value); }

  public boolean headersOnly() {
    return headOnly;
  }

  public void headersOnly(boolean headOnly) {
    this.headOnly = headOnly;
  }

  public String getHeader() {
    String ret;
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG,
        DateFormat.LONG);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));

    fields.put("Date", df.format(new Date()));
    if (!fields.containsKey("Last-Modified")) {
      fields.put("Last-Modified", df.format(new Date()));
    }
    if (!fields.containsKey("Content-Type")) {
      fields.put("Content-Type", "text/html");
    }
    fields.put("Server", Main.name+"/"+Main.version);

    ret = "HTTP/1.1 "+getStatus()+CRLF;

    Enumeration<String> keys = fields.keys();

    while (keys.hasMoreElements()) {
      String key = keys.nextElement();
      String val = fields.get(key);
      
      ret += key+": "+val+CRLF;
    }

    ret += CRLF;

    return ret;
  }

  public boolean headerSent() {
    return headerIsSent;
  }

  public void headerSent(boolean isSent) {
    headerIsSent = isSent;
  }

}
